
$(document).ready(function() {
	$(".grouped-form input")
		.removeClass("text-active")
		.click(function() { $(this).addClass("text-active"); })
		.blur(function() {
			var jObj = $(this);
			jObj.removeClass("text-active");
			if ($.trim(jObj.val()) == "") jObj.val("1");
		});
});


var viewModel = new function () {
    // DEBUG
    //if (typeof console != "undefined") console.log(data);
    this.data = ko.observableArray(data.EmailTemplateInfo);
    this.SetOrder = SetOrder;
    this.ColName = ko.observable("TemplateTitle");
    this.SortOrder = ko.observable("asc");

    this.DateTimeNow = ko.observable(GetCurrentTime());
    this.EmailStatistics = ko.observable(data.EmailStatistics.EmailVolumeAdditionalEnabled);
    this.EmailVolumeAdditionalCost = ko.observable(data.EmailStatistics.EmailVolumeAdditionalCost);
    this.EmailVolumeAdditionalEnabled = ko.observable(data.EmailStatistics.EmailVolumeAdditionalEnabled);

    this.MonthlyAllowance = ko.observable(formatCurrency("#,##0.##", data.EmailStatistics.MonthlyAllowance));
    this.RemainingAllowance = ko.observable(formatCurrency("#,##0.##", data.EmailStatistics.RemainingAllowance));
    this.EmailsSent = ko.observable(formatCurrency("#,##0.##", data.EmailStatistics.EmailsSent));
    this.TemplatesQueued = ko.observable(formatCurrency("#,##0.##", data.EmailStatistics.TemplatesQueued));


    // Calculate condition to add class
    // Fix issue in chrome
    this.LineClass = function (index, length, status) {
        if (status == "Enabled") {
            if (index == length)
                return "selected-line line last";
            else
                return "selected-line line";
        }
        else {
            if (index == length)
                return "line last";
            else
                return "line";
        }
    }

    this.CurrentPageIndex = ko.observable(1);
    this.PageSize = ko.observable(10);


    // Insert max page
    this.MaxPageIndex = ko.computed(function () {
        return Math.ceil(ko.utils.unwrapObservable(this.data()).length / this.PageSize());
    }, this);

    this.listEmailItems = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, ''),
			pagesize = parseInt(pagevalue, 10);

        if (isNaN(pagesize) || pagesize < 1 || pagesize > 100) {
            return "";
        }
        else {
            var startIndex = this.PageSize() * (this.CurrentPageIndex() - 1),
				endIndex = parseInt(startIndex) + parseInt(this.PageSize());

            return this.data().slice(startIndex, endIndex);
        }
    }, this);


    // Handle checked / un-checked an email-template event
    var OnSelectedEmailTemplate = function () {
        var jObj = $(this);
        UpdateTableLayoutByCheckbox(jObj);

        // Update status
        if (jObj.attr("id") && !isNaN(parseInt(jObj.attr("id")))) {
            UpdateEmailTemplateStatus(jObj.attr("id"), jObj.is(":checked"), function () {
                // DEBUG
                if (typeof console != "undefined")
                    console.log("UpdateEmailTemplateStatus(), jQuery.ajax postback error;  checkbox.checked => " + !jObj.is(":checked"));

                // Toggle back the checkbox when the AJAX postback error
                jObj.get(0).checked = !jObj.is(":checked");
                UpdateTableLayoutByCheckbox(jObj);

                if (typeof jObj.get(0).jcf != "undefined" && jObj.get(0).jcf) {
                    jObj.get(0).jcf.refreshState();
                }
            });
        }
    };

    this.afterRenderEmailRows = function (els) {
        // DEBUG
        //if (typeof console != "undefined") console.log("afterRenderEmailRows(), A row was rendered.");
        if (els && els.length) {
            for (var i = 0; i < els.length; i++) {

                // Replace browser checkboxs with JCF checkboxs
                $(".col1 input:checkbox, .col1 select", els[i]).each(function (idx, el) {
                    el = $(el);
                    if ((typeof el.get(0).jcf == "undefined" || !el.get(0).jcf) && el.attr("id")) {
                        // DEBUG
                        //if (typeof console != "undefined") console.log("afterRenderEmailRows(), JCF.replaceElement: " + el.attr("id"));
                        jcf.customForms.replaceElement(el.attr("id"));
                        setTimeout("jcf.customForms.replaceElement('" + el.attr("id") + "');", 0);
                    }

                    // Toggle the current table-row style on the checkbox was (un)selected
                    if (el.is(":checkbox")) {
                        el.unbind("change", OnSelectedEmailTemplate).bind("change", OnSelectedEmailTemplate);
                    }
                });
            }
        }
    };

    ///////////////////// Paging /////////////////////////////
    this.PageSizeText = ko.computed(function () {

        var pagevalue = this.PageSize().toString().replace(/\s/g, ''),
			pagesize = parseInt(pagevalue, 10);
        this.CurrentPageIndex(1);

        if (!IsNumeric(pagevalue)) {
            return "* Please enter a number between 1 - 100";
        }
        else if (isNaN(pagesize) || pagesize < 1 || pagesize > 100) {
            return "* Please enter a number between 1 - 100";
        }
        else {
            return "";
        }
    }, this);

    this.PageCurrentText = ko.computed(function () {
        var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, ''),
			pageindex = parseInt(pagevalue, 10);

        if (!IsNumeric(this.CurrentPageIndex()) || pagevalue == "") {
            return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
        }
        else if (isNaN(pagevalue) || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
            return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
        }
        else {
            return "";
        }

    }, this);

    this.PrevPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            this.CurrentPageIndex(page - 1);
        }
    }
    this.NextPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page < this.MaxPageIndex()) {
            this.CurrentPageIndex(page + 1);
        }
    }

    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        return (page > 1) ? "btn btn-prev-arrow prev-active" : "btn btn-prev-arrow";
    }, this);

    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
            return "btn btn-next-arrow next-disabled";
        else
            return "btn btn-next-arrow";
    }, this);

    // PageSize/ PageCurrent keypress enter
    this.RunSomethingKey = function (viewModel, event) {
        if (event.keyCode == 13) {
            this.RunSomething(viewModel, event);
        }
        return true;
    }

    this.RunSomething = function (viewModel, event) {
        return true;
        LoadDataKeyPresss();
    }

    function LoadDataKeyPresss() {
        // Page Size
        var pageSizeValue = $('#pagesize').val().toString().replace(/\s/g, ''),
			pagesize = parseInt(pageSizeValue, 10);
        if (!IsNumeric(pageSizeValue) || isNaN(pagesize) || pagesize < 1 || pagesize > 100) {
            return false;
        }

        // Page Index
        var pageIndexValue = $('#pagecurrent').val().toString().replace(/\s/g, ''),
			pageindex = parseInt(pageIndexValue, 10);
        if (!IsNumeric(pageIndexValue) || isNaN(pageindex) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            return false;
        }
    }

    ////// Sorting ///////
    function SetTHClass(event, colName) {
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc desc");

        if (viewModel.SortOrder() === "asc") {
            $("#" + colName).children("span").addClass("asc");
        }
        else {
            $("#" + colName).children("span").addClass("desc");
        }
    }

    function SwitchSortOrder() {
        if (this.SortOrder() === "asc") {
            this.SortOrder("desc");
        }
        else {
            this.SortOrder("asc");
        }
    }
    this.SwitchSortOrder = SwitchSortOrder;

    function SetOrder(event, ColName) {
        if (this.ColName() === ColName) {
            this.SwitchSortOrder();
        }
        else {
            this.ColName(ColName);
            this.SortOrder("asc");
        }
        SetTHClass(event, ColName);

        if (ColName != "") {
            this.data(SortByPropertyName(ko.utils.unwrapObservable(this.data()), ColName, this.SortOrder()));
        }
    }

    // sort all items
    function SortByPropertyName(items, propertyName, sortOrder) {
        return items.sort(sortProperty(propertyName, sortOrder));
    }
    function sortProperty(property, sortOrder) {
        if (sortOrder == "asc") {
            return function (a, b) {
                var number = parseFloat($.trim(a[property])),
					numberb = parseFloat($.trim(b[property]));

                if (!isNaN(number) && number > 0 && number.toString().length == a[property].toString().length) {
                    return (number < numberb) ? -1 : ((number > numberb) ? 1 : 0);
                }
                else {
                    return (a[property].toLowerCase() < b[property].toLowerCase()) ? -1
						: ((a[property].toLowerCase() > b[property].toLowerCase()) ? 1 : 0);
                }
            }
        }
        else {
            return function (a, b) {
                var number = parseFloat($.trim(a[property])),
					numberb = parseFloat($.trim(b[property]));

                if (!isNaN(number) && number > 0 && number.toString().length == a[property].toString().length) {
                    return (number > numberb) ? -1 : ((number < numberb) ? 1 : 0);
                }
                else {
                    return (a[property].toLowerCase() > b[property].toLowerCase()) ? -1
						: ((a[property].toLowerCase() < b[property].toLowerCase()) ? 1 : 0);
                }
            }
        }
    }
}

ko.applyBindings(viewModel, document.getElementById("email"));


////////// Private Method //////////////
// Update new function
// Comment old function
function UpdateEmailSending() {
	var enable = $("#chkEmailSending").is(":checked");

	$.getJSON('/Email/UpdateEmailSending/' + enable, function(returnData) {
		// DEBUG
		//if (typeof console != "undefined") console.log(returnData);
		if (returnData && typeof returnData.MonthlyAllowance != "undefined") {

			viewModel.MonthlyAllowance(formatCurrency("#,##0.##", returnData.MonthlyAllowance));
			viewModel.RemainingAllowance(formatCurrency("#,##0.##", returnData.RemainingAllowance));
			viewModel.EmailsSent(formatCurrency("#,##0.##", returnData.EmailsSent));
			viewModel.TemplatesQueued(formatCurrency("#,##0.##", returnData.TemplatesQueued));

			//$("#chkEmailSending").attr("checked", (!enable) ? "false" : "true");
		}
		else if (returnData) {
			// Display error message
			alert(returnData);
		}
	});
}

function UpdateTableLayoutByCheckbox(chk) {
	if (chk.is(":checked")) {
		chk.parents(".col1:first").parent().removeClass("line").addClass("selected-line");
	}
	else {
		chk.parents(".col1:first").parent().removeClass("selected-line").addClass("line");
	}
}

// Update manage email template status.
function UpdateEmailTemplateStatus(templateId, isChecked, errorHandler) {
	var enable = (!isChecked) ? "Disabled" : "Enabled";

	var jqxhr = $.getJSON('/Email/UpdateStatus/' + templateId + '/' + enable, function(resultData) {
		// DEBUG
		if (typeof console != "undefined")
			console.log("UpdateEmailTemplateStatus(), resultData.type: " + (typeof resultData) + ", resultData: " + JSON.stringify(resultData));

		if (typeof resultData != "undefined" && (resultData === "" || typeof resultData.Error == "undefined" || !resultData.Error)
			&& typeof data != "undefined" && data.EmailTemplateInfo) {

			for (var i = 0; i < data.EmailTemplateInfo.length; i++) {

				if (data.EmailTemplateInfo[i].TemplateId == templateId) {
					data.EmailTemplateInfo[i].Status = enable;
					break;
				}
			}
		}
		else if (typeof errorHandler == "function") {
			errorHandler.call();
		}
	});

	if (typeof errorHandler == "function") {
		jqxhr.error(errorHandler);
	}
}

function GetCurrentTime() {
	var months = ["January", "February", "March", "April", "May", "June",
				"July", "August", "September", "October", "November", "December"],
		currentTime = new Date(),
		monthIndex = currentTime.getMonth(),
		year = currentTime.getFullYear();

	return months[monthIndex] + " " + year;
}

